package com.fqr;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.exolab.castor.core.exceptions.CastorException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.XMLException;

public class FlexSchedule implements TriggerListener {

	private static Logger logger = Logger.getLogger(FlexSchedule.class);

	private List<FlexJob> flexJobs = new ArrayList<FlexJob>();
	private List<FlexTrigger> flexTriggers = new ArrayList<FlexTrigger>();

	private Information information;

	public Information getInformation() {
		return information;
	}

	public void setInformation(Information information) {
		this.information = information;
	}

	public List<FlexJob> getFlexJobs() {
		return flexJobs;
	}

	public List<FlexTrigger> getFlexTriggers() {
		return flexTriggers;
	}

	public void start() {
		for (FlexTrigger trigger : flexTriggers)
			trigger.setListener(this);

		logger.info("Schedule is started");
	}

	public void onFire(TriggerEvent event) {
		logger.info(event.getTrigger().getName() + " fired");
		String targetJobName = event.getTrigger().getTargetJobName();

		for (FlexJob job : flexJobs) {
			if (job.getName().equals(targetJobName)) {
				logger.info(event.getTrigger().getName() + " triggers "
						+ job.getName());

				Thread t = new Thread(job);
				GlobalContext.put(t.getId() + "." + job.getName(), event
						.getEventDetail());
				t.setDaemon(true);
				t.start();
			}
		}
	}

	public void runJob(String jobName, Object data) {
		for (FlexJob job : flexJobs) {
			if (job.getName().equals(jobName)) {
				logger.info("run " + job.getName());

				GlobalContext.put(Thread.currentThread().getId() + "."
						+ job.getName(), data);
				job.run();
			}
		}
	}

	private static FlexSchedule sched;

	public static FlexSchedule getSchedule() throws CastorException,
			IOException {
		if (sched == null) {
			InputStream is = FlexSchedule.class.getClassLoader()
					.getResourceAsStream("flex_jobs.xml");
			createSchedule(is);
		}

		return sched;
	}

	static FlexSchedule createSchedule(InputStream is) throws XMLException,
			IOException {
		InputStreamReader reader = new InputStreamReader(is);
		sched = (FlexSchedule) Unmarshaller.unmarshal(FlexSchedule.class,
				reader);
		is.close();

		logger.info("Schedule is created");

		return sched;
	}

}
